package cn.highset.common.utils.wechat;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
public class WxMaCryptUtils extends WxCryptUtil {

    /**
     * AES解密
     *
     * @param encryptedData 消息密文
     * @param ivStr         iv字符串
     */
    public static String decrypt(String sessionKey, String encryptedData, String ivStr) {
        try {
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(Base64.decodeBase64(ivStr)));

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params);

            return new String(PKCS7Encoder.decode(cipher.doFinal(Base64.decodeBase64(encryptedData))), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("AES解密失败", e);
        }

    }

    public static void main(String[] args) {

//        String encryptedData = "ZeeKOqZkt8Fn0sQzSqt7si6j7M5sia+prG52GGxPOjdBcTi9koqXVPQvBs90S4DjI4mBLhvlUHulxQMtZ8QwXEVTYkXEsy4Muz4yrO+KjLowHlT3X+nj7y1ttHrMGL3YAsUYLNJRqdU+PKeasFGnUoHKwwblzHYgIjXCdi/neAMg9n3O+KW6rPryUD+kiVcC8K3CvkAqVYwVyiy+LRqaB2+UMlGVq6hSWy2YFQPd5qwZ35ah+kHs0dBlokR/A6YmK8j64r29zdqfQJmZhXgo0+iPZR35Ye/2N/AUvDjpwzZ/pmTU8XO3F88uqx6t9paRvhMf5d7A1yW0pEOMI8m42UFowcFQ38peC5kffidXSYSkSYRk4cKEGoEB7BLhYdJU9dg7KnVMIjUSPOYlX7KTVcavHBKd8knUcXHdOsSYzlSaVyPDcWR6snooyfH7JwVSbVw5wiEKd+AbzGpIulhwJC+5T3jkRQ2RAzMkZ2nK2xBAI8CZtSl3d6OldPbZRGWG6uPniKVpaW3p1C3C9Mz6Ag==";
//        String sessionKey = "XQTv90DCc6TpFwwgwXVmuw==";
//        String iv = "bVl0yi6M2RvnMgN7XpSO5g==";
//        System.out.println(WxMaCryptUtils.decrypt(sessionKey,encryptedData,iv));


        String encryptedData = "0951iJHMuMZQ3CXZ96yunhcx1gRe6mU3bKrT16GL7kEISlGKCyoKaWCrHQUHKlCaFBKoWiWXqtDoqJ5uo5fuHFHDNA0Ygo0uW2CguO6u6zn4P6zJlWDnPGDbKn7ndq2uCz5b2OjPNKOup0RgTxD3lAr4OjyBIF4K2VYQNoKvZDzmHRMqOONQLayu1RrsuiGALAyPZ2+Ky39Br1vmhFD6kA==";
        String sessionKey = "RcvN4psCcBUAM93IVAlx9Q==";
        String iv = "ZesisqYOjYQbMCtALeQplw==";
        System.out.println(WxMaCryptUtils.decrypt(sessionKey, encryptedData, iv));
    }

}
